import json
from PyQt5.QtWidgets import (
    QHBoxLayout,
    QVBoxLayout,
    QLabel,
    QHeaderView,
    QGridLayout,
    QPushButton,
    QFileDialog,
    QComboBox,
    QFrame,
    QGroupBox,
    QAbstractItemView,
    QTableWidgetItem,
    QTableWidget,
    QSpacerItem,
    QWidget,
    QDialog,
    QCheckBox,
)
from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QObject, QEvent
from PyQt5.QtGui import QPainter, QPen, QColor, QDoubleValidator
from pydantic import BaseModel, Field, field_validator

# import pandas as pd
import csv
import gui.controls.envs as envs

# import gui.controls.envs as envs
from ..dlg_model_params import DlgModelParams

# from ..dlg_mulit_instance import DlgMutliInstance
from ..c_params_table import CParamsTable

# from plugins.DUT_tiankuo.ipimas.params_model.dlg_params import DlgParams
from ..dlg_params import DlgParams
from ..util.file_operation import FileOperation
from ..custom_widget import LineEditFloat, LineEditStr, LineEditInt, SelectBox

typeMap = {
    "Laminate": "层合板",
    "Honeycomb": "蜂窝",
    "Metal": "金属",
    "胶层": "胶层",
}


class CustomTable(CParamsTable):

    def __init__(self, rows=0, columns=2, parent=None):
        super(CustomTable, self).__init__(rows=rows, columns=columns, parent=parent)
        self.verticalHeader().setVisible(True)
        self.setEditTriggers(QTableWidget.NoEditTriggers)

    def addRow(self, key, data):
        rowIdx = self.rowCount()
        self.insertRow(rowIdx)
        for column in range(self.columnCount()):
            if column == 0:
                checkbox = QCheckBox()
                checkbox.setChecked(data.get("selected"))
                container = QWidget()
                layout = QHBoxLayout(container)
                layout.setContentsMargins(0, 0, 0, 0)  # 移除布局的边距
                layout.setAlignment(Qt.AlignCenter)  # 设置布局居中
                layout.addWidget(checkbox)
                self.setCellWidget(rowIdx, column, container)
            elif column == 1:
                item = QTableWidgetItem(data.get("材料名称"))
                item.setTextAlignment(Qt.AlignCenter)
                self.setItem(rowIdx, column, item)
                item.setData(Qt.UserRole, key)
            elif column == 2:
                item = QTableWidgetItem(typeMap.get(data.get("材料类型")))
                item.setTextAlignment(Qt.AlignCenter)
                self.setItem(rowIdx, column, item)

    def getRowData(self, row):
        list = []
        if row > self.rowCount() - 1:
            return None
        for col in range(self.columnCount()):
            if col == 0:
                wrapWidget = self.cellWidget(row, col)
                wrapLayout = wrapWidget.layout()
                selectBox = wrapLayout.itemAt(0).widget()
                list.append(selectBox.isChecked())
            else:
                item = self.item(row, col)
                if item is not None:
                    list.append(self.getRuleValue(item.text(), col))
                else:
                    list.append(None)
        return list

    def getSelectData(self):
        res = []
        for row in range(self.rowCount()):

            wrapWidget = self.cellWidget(row, 0)
            wrapLayout = wrapWidget.layout()
            selectBox = wrapLayout.itemAt(0).widget()
            if selectBox.isChecked():
                keyItem = self.item(row, 1)
                if keyItem:
                    res.append(keyItem.data(Qt.UserRole))
        return res


class DlgMaterialSelect(QDialog):
    materialSelect_save_signal = pyqtSignal(object)

    def __init__(self, parent=None):
        super(DlgMaterialSelect, self).__init__(parent)
        self.setWindowTitle("材料库")
        self.setMinimumWidth(600)
        self.setMinimumHeight(600)

        # 创建垂直布局
        layout = QVBoxLayout()
        self.widgetDict = {}

        self.data = [
            {"title": ""},
            {"name": "name", "title": "名称", "type": "str", "require": True},
            {"name": "poissonRatio", "title": "类型", "type": "str"},
        ]

        self.headerLabels = []
        for lab in self.data:
            self.headerLabels.append(lab.get("title"))

        self.table = CustomTable(rows=0, columns=len(self.headerLabels))
        self.table.setHorizontalHeaderLabels(self.headerLabels)
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Interactive)
        header = self.table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.Fixed)  # 设置第一列宽度固定
        header.resizeSection(0, 30)  # 设置固定宽度为 50 像素

        # self.table.setColumnWidth(0, 160)
        layout.addWidget(self.table)

        btnLayout = QHBoxLayout()
        btnLayout.setAlignment(Qt.AlignCenter)
        okBtn = QPushButton("确认")
        cancelBtn = QPushButton("取消")
        okBtn.setFocusPolicy(Qt.NoFocus)
        cancelBtn.setFocusPolicy(Qt.NoFocus)
        btnLayout.addWidget(okBtn)
        btnLayout.addWidget(cancelBtn)
        layout.addLayout(btnLayout)

        okBtn.clicked.connect(self.on_okBtn_clicked)
        cancelBtn.clicked.connect(self.close)

        self.setLayout(layout)

    def init(self, dataDict):

        self.loadData(dataDict)

    def on_okBtn_clicked(self):
        res = self.table.getSelectData()
        self.materialSelect_save_signal.emit(res)
        self.close()

    def on_cancelBtn_clicked(self):
        pass

    def loadData(self, dataDict):
        self.table.setRowCount(0)
        if dataDict:
            for key, rowData in dataDict.items():
                self.table.addRow(key, rowData)

    def closeEvent(self, event):
        DlgMaterialSelect._shown = False  # 使用类名访问类属性
        DlgMaterialSelect._instance = None  # 清除实例引用
        event.accept()
